#ifndef THREADBASE_H
#define THREADBASE_H

extern "C"
{
#include <pthread.h>
#include <semaphore.h>
}
typedef struct _ThreadDataExcangeContext
{
    unsigned char* buffer; // buffer pointer
    unsigned long data_size; // buffer size
    pthread_mutex_t mutex; // mutex lock
    sem_t sem; // semaphore
} ThreadDataExcangeContext;

//线程基类
class ThreadBase
{
public:
    ThreadBase(); //构造函数
    virtual ~ThreadBase(); //虚析构函数

    virtual int start(); //启动线程
    virtual void routine(); //线程的运行函数，由派生类实现
    virtual pthread_t self(); //获取当前线程的线程号
    virtual int equal(pthread_t t); //比较线程号是否相等
    virtual int detach(); //分离线程
    virtual int join(pthread_t t); //连接线程
    virtual int exit(); //线程退出
    virtual int cancel(pthread_t t); //取消线程
    virtual int destroy(); //销毁线程
    void init_output_context(unsigned long data_size);
    ThreadDataExcangeContext* get_output_context();
    void init_input_context(ThreadDataExcangeContext* context);

    void free_output_context();

    void lock_input_buffer();
    void unlock_input_buffer();

    void lock_output_buffer();
    void unlock_output_buffer();

    void wait_input_new_message();
    unsigned char try_input_new_message();
    void set_output_new_message(unsigned char flag);
    unsigned long get_input_size();
    unsigned long get_output_size();
    void get_input_buffer(unsigned char* dst);
    void write_output_buffer(unsigned char* buffer);



private:
    static void cleaner(void *pHandle); //线程清理函数
    static void *work(void *pHandle); //线程回调函数

private:
    pthread_attr_t  t_attr; //线程属性
    pthread_t tid; //线程号
    ThreadDataExcangeContext *m_input_context;
    ThreadDataExcangeContext m_output_context;

};

#endif // THREADBASE_H
